package com.zds.scm.service.impl;

import org.apache.log4j.Logger;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import com.zds.scm.common.service.ServiceException;
import com.zds.scm.dao.UserInfoDAO;
import com.zds.scm.dao.impl.UserInfoDAOImpl;
import com.zds.scm.domain.UserInfo;
import com.zds.scm.service.UserInfoService;
import static com.zds.scm.common.util.StringUtils.*;

public class UserInfoServiceImpl implements UserInfoService {

	private static final Logger logger = Logger.getLogger(UserInfoServiceImpl.class);

	private UserInfoDAO userInfoDAO=new UserInfoDAOImpl();
	@Override
	public boolean delete(Serializable id) {
		UserInfo userInfo=new UserInfo();
		userInfo.setUserCode(id.toString());
		return userInfoDAO.delete(userInfo);
	}

	@Override
	public List<UserInfo> findAll() {
		return userInfoDAO.findAll();
	}

	@Override
	public UserInfo findById(Serializable id) {
		return userInfoDAO.findById(id);
	}

	@Override
	public boolean insert(UserInfo t) {
		return userInfoDAO.insert(t);
	}

	@Override
	public boolean update(UserInfo t) {
		return userInfoDAO.update(t);
	}

	@Override
	public void login(UserInfo userInfo) throws ServiceException {
		UserInfo userInfo2=userInfoDAO.findById(userInfo.getUserCode());
		if(userInfo2==null||userInfo==null){
			logger.debug("找不到账号");
			throw new ServiceException("找不到账号");
		}else if (!userInfo.getUserPwd().equals(userInfo2.getUserPwd())) {
			logger.debug("密码不一致:实际密码为"+userInfo2.getUserPwd());
			throw new ServiceException("账号密码不匹配");
		}
		try {
			BeanUtils.copyProperties(userInfo2, userInfo);
		} catch (Exception e) {
			logger.error("复制实体出现错误");
			throw new ServiceException("复制实体出现错误:"+e.getMessage());
		}
	}

	@Override
	public void changePwd(String userCode,String userPwd,String userNewPwd) {
		if(isNull(userCode)||isNull(userPwd)||isNull(userNewPwd)){
			logger.debug("账号/原密码/新密码都不能为空");
			throw new ServiceException("账号/原密码/新密码都不能为空");
		}
		if (userPwd.equals(userNewPwd)) {
			logger.debug("新密码和原密码是一样的，不需要修改");
			throw new ServiceException("新密码和原密码是一样的，不需要修改");
		}
		UserInfo userInfo=userInfoDAO.findById(userCode);
		if(isNull(userInfo)){
			logger.debug("找不到该账号,修改密码失败");
			throw new ServiceException("找不到该账号,修改密码失败");
		}
		if (!userInfo.getUserPwd().equals(userPwd)) {
			logger.debug("输入的原密码不正确,修改密码失败:"+userPwd);
			throw new ServiceException("输入的原密码不正确,修改密码失败");
		}
		userInfo.setUserPwd(userNewPwd);
		if(!userInfoDAO.update(userInfo)){
			logger.debug("密码修改失败");
			throw new ServiceException("执行修改失败,修改密码失败");
		}
	}

}
